<template>
  <div ref="revdrawRef" class="w-full h-full">
    <!-- <Revedraw
      :dataSource="dataSource"
      canvasName="test"
      :getRef="(ref) => setRef('revdrawRef')"
      :systemLangCode="systemLangCode"
      :onChange="onChangeDebounceFn"
      :onLinkOpen="onLinkOpen"
    /> -->
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import { Revedraw } from 'revemate';
import React from 'react';
import ReactDOM from 'react-dom';
import { boardIndexeddbStorage } from '@renderer/store/boardIndexeddb';
import { useDebounceFn } from '@vueuse/core';

import { langCodeAtom } from '@renderer/store/jotai';
import { useAtom } from 'jotai-vue';
import { getOSName } from '@renderer/utils/navigator';
import { emitter } from '@renderer/store/eventemitter';
import useDoubleLink from '@renderer/hooks/useDoubleLink';
import useFileTree from '@renderer/hooks/useFileTree';

import './index.css';

const props = defineProps({
  file: {
    type: Object,
    required: true,
  },
});

const OS_NAME = getOSName();

const dataSource = ref(null);
const refElement = ref(null);
const revdrawRef = ref();
const systemLangCode = useAtom(langCodeAtom)[0];
const didRender = ref(true);
const { onLinkOpen } = useDoubleLink(true);
const { fileTree } = useFileTree();

const excalidrawRef = ref(null);

function setRef(ref) {
  console.log(ref, 'setRef');
  excalidrawRef.value = revdrawRef.value;
}

const clearDeletedElements = (data) => {
  data.elements?.forEach((element) => {
    if (element?.isDeleted) {
      delete data.files?.[element.fileId];
    }
  });

  data.elements = data.elements?.filter((element) => !element.isDeleted);

  return data;
};

const getDataSource = async (id) => {
  dataSource.value = null;

  let data = await boardIndexeddbStorage.getBoard(id);

  data = clearDeletedElements(data);

  const dataStr = !data || typeof data === 'string' ? data : JSON.stringify(data);

  dataSource.value = dataStr;
};
const onChangeFn = async (data) => {
  const _data = {
    type: 'excalidraw',
    version: 2,
    source: window.location.href,
    ...data,
  };

  await boardIndexeddbStorage.updateBoard(props.file.id, _data, fileTree);
};
const { run: onChangeDebounceFn, cancel: cancelDebounceFn } = useDebounceFn(onChangeFn, {
  wait: 200,
});
console.log(onChangeDebounceFn,'onChangeDebounceFn');

const rerender = async () => {
  const WAIT_TIME_WINDWOS = 500;
  const WAIT_TIME_MACOS = 200;

  const waitTime = OS_NAME === 'MacOS' ? WAIT_TIME_MACOS : WAIT_TIME_WINDWOS;

  // await getDataSource(props.file.id);
  console.log('rerender', revdrawRef.value);
  let json = {theme: 'light', langCode: 'zh-CN', libraryItems: []}
  setTimeout(() => {
    didRender.value = false;
    setTimeout(() => {
      didRender.value = true;
      // ReactDOM.render(<Revedraw dataSource={dataSource} canvasName={'test'} getRef={(ref) => setRef('revdrawRef')} systemLangCode={systemLangCode} onChange={onChangeDebounceFn} onLinkOpen={onLinkOpen} />, revdrawRef.value);
        const root = ReactDOM.createRoot(revdrawRef.value)
        root.render(React.createElement(Revedraw, {
          dataSource: json,
          canvasName: 'test',
          getRef: (ref) => setRef('revdrawRef'),
          systemLangCode: systemLangCode,
          onChange: (e) => {},
          onLinkOpen: onLinkOpen,
        }))
    }, 100);
  }, waitTime);
};




onMounted(() => {
  setTimeout(() => {
    rerender();
  }, 1000);
  emitter.on('switch_font_family', rerender);
});

onBeforeUnmount(() => {
  cancelDebounceFn();
  emitter.off('switch_font_family', rerender);
});

// watch(() => props.file.id, (newId) => {
//   getDataSource(newId);
// });
</script>
